package com.ops.service.ns.system.beans;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpSession;

import com.ops.schema.ns.system.LoginRequest;
import com.ops.schema.ns.system.LoginResponse;
import com.ops.schema.ns.system.LogoutRequest;
import com.ops.schema.ns.system.LogoutResponse;
import com.ops.schema.ns.system.OPSMenu;
import com.ops.schema.ns.system.OPSRole;
import com.ops.schema.ns.system.OPSUser;
import com.ops.service.ns.system.client.OnlinePayrollSystemServiceClient;
import com.ops.service.ns.system.constants.ParamConstants;
import com.ops.service.ns.system.exception.ServiceException;

public class LoginMBean {

	private String userId;
	private String password;
	private List<OPSMenu> menus;
	private OPSUser user;
	private String userRole;
	private OPSRole role;
	private String status;
	private List<OPSRole> roleList;
	private List<SelectItem> userRoles;

	
	public String getUserRole() {
		return userRole;
	}

	public void setUserRole(String userRole) {
		this.userRole = userRole;
	}

	public OPSRole getRole() {
		return role;
	}

	public void setRole(OPSRole role) {
		this.role = role;
	}

	public List<SelectItem> getUserRoles() {
		if (userRoles == null) {
			if (roleList != null) {
				userRoles = new ArrayList<SelectItem>();
				for (OPSRole roles : roleList) {
					SelectItem item = new SelectItem(roles.getId(),
							roles.getName());
					userRoles.add(item);
				}
			}
		}
		return userRoles;
	}

	public void setUserRoles(List<SelectItem> userRoles) {
		this.userRoles = userRoles;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public List<OPSRole> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<OPSRole> roleList) {
		this.roleList = roleList;
	}

	/**
	 * @return the userId
	 */
	public String getUserId() {
		return userId;
	}

	/**
	 * @param userId
	 *            the userId to set
	 */
	public void setUserId(String userId) {
		this.userId = userId;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password
	 *            the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the menus
	 */
	public List<OPSMenu> getMenus() {
		return menus;
	}

	/**
	 * @param menus
	 *            the menus to set
	 */
	public void setMenus(List<OPSMenu> menus) {
		this.menus = menus;
	}

	public OPSUser getUser() {
		return user;
	}

	public void setUser(OPSUser user) {
		this.user = user;
	}

	

	public void login(ActionEvent event) {
		System.out.println("Inside Login");
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext eContext = context.getExternalContext();
		Map<String, Object> sessionMap = eContext.getSessionMap();
		sessionMap.put("RoleId", getUserRole());
		
		System.out.println("Session::Role::"+sessionMap.get("RoleId"));
		for(OPSRole role_u : roleList)
		{
			if(role_u.getId().equalsIgnoreCase(getUserRole()))
			{
				setRole(role_u);
				break;
			}
			
		}
		System.out.println("Exit Login");
	}

	public void resetLogin() {
		setStatus(null);
		setUserId(null);
		setPassword(null);
		System.out.println("Inside resetLogin");
	}

	public void validateLogin() {

		userIdValidation();

		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext eContext = context.getExternalContext();
		HttpSession session = (HttpSession) eContext.getSession(false);
		Map<String, Object> sessionMap = eContext.getSessionMap();
		sessionMap.put("UserId", userId);
		LoginRequest loginRequest = new LoginRequest();
		loginRequest.setUserId(userId);
		loginRequest.setPassword(password);
		loginRequest.setUserSession(session.getId());
		try {
			LoginResponse loginResponse = OnlinePayrollSystemServiceClient
					.login(loginRequest);

			System.out.println("Status:::"
					+ loginResponse.getServiceResult().getStatusCode());
			if (!(loginResponse != null
					&& loginResponse.getServiceResult() != null
					&& loginResponse.getServiceResult().getStatusCode() != null && loginResponse
					.getServiceResult().getStatusCode()
					.equals(ParamConstants.OPS_SERVICE_SUCCESS_CODE))) {
				System.out.println("Inside:1"
						+ loginResponse.getServiceResult().getStatusCode());
				if (loginResponse != null
						&& loginResponse.getServiceResult() != null
						&& loginResponse.getServiceResult().getStatusMsg() != null) {
					System.out.println("Inside:2"
							+ loginResponse.getServiceResult().getStatusCode());
					processError(loginResponse.getServiceResult()
							.getStatusMsg());

				} else {
					System.out.println("Inside:3"
							+ loginResponse.getServiceResult().getStatusCode());
					processError(null);

				}
			} else {
				System.out.println("Inside:4"
						+ loginResponse.getServiceResult().getStatusCode());
				setMenus(loginResponse.getOPSMenu());
				setUser(loginResponse.getOPSUser());
				setRoleList(loginResponse.getOPSRole());
				setStatus(loginResponse.getServiceResult().getStatusCode());
			}

		} catch (ServiceException ex) {
			processError(null);
		}
	}

	public void processError(String error) {

		FacesContext context = FacesContext.getCurrentInstance();

		UIViewRoot viewRoot = context.getViewRoot();
		UIComponent component = viewRoot
				.findComponent("loginform:validateForm");

		FacesMessage message = new FacesMessage();
		message.setSeverity(FacesMessage.SEVERITY_ERROR);
		if (error != null) {
			message.setSummary(error);
			message.setDetail(error);
		} else {
			message.setSummary(ParamConstants.OPS_SERVICE_TECHNICAL_EXCEPTION_MESSAGE
					+ "generic exception during login");
			message.setDetail(ParamConstants.OPS_SERVICE_TECHNICAL_EXCEPTION_MESSAGE
					+ "generic exception during login");
		}
		context.addMessage(component.getClientId(context), message);
		// throw new ValidatorException(message);
	}

	public void logOut(ActionEvent event) {

		try {
			FacesContext context = FacesContext.getCurrentInstance();
			HttpSession session = (HttpSession) context.getExternalContext()
					.getSession(false);
			Map<String, Object> sessionMap = context.getExternalContext()
					.getSessionMap();
			LogoutRequest logoutRequest = new LogoutRequest();
			logoutRequest.setUserId(sessionMap.get("UserId").toString());
			logoutRequest.setUserSession(session.getId());
			LogoutResponse response = OnlinePayrollSystemServiceClient
					.logout(logoutRequest);
			System.out.println(response.getServiceResult().getStatusMsg());
			session.invalidate();
			context.getExternalContext().redirect(
					context.getExternalContext().getRequestContextPath()
							+ "/login.jspx");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void userIdValidation() {

		FacesContext context = FacesContext.getCurrentInstance();

		UIViewRoot viewRoot = context.getViewRoot();
		UIComponent component = viewRoot.findComponent("loginform:userId");

		FacesMessage message = new FacesMessage();
		message.setSeverity(FacesMessage.SEVERITY_ERROR);
		if (userId != null) {
			try {
				new BigInteger(userId);
			} catch (NumberFormatException ex) {
				message.setSummary("User Name must be a number");
				message.setDetail("User Name must be a number");
				context.addMessage(component.getClientId(context), message);
				throw new ValidatorException(message);
			}
		}
	}
}
